﻿using Hrm.Api.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace Hrm.Api.Controllers
{
    public class LoginController : ApiController
    {
        [HttpGet]
        public string Get()
        {
            AuthenticationManager.SignOut();
            return "Success";
        }

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.Current.GetOwinContext().Authentication;
            }
        }

        UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        [HttpPost]
        public HttpResponseMessage PostLogin(LoginViewModel model)
        {
            var user = UserManager.Find(model.UserName, model.Password);
            if (user != null)
            {
                var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
                //FormsAuthentication.SetAuthCookie(model.UserName, false);
                return Request.CreateResponse(HttpStatusCode.OK, "S");
            }

            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid username or password.");
            }
        }
    }
}
